import './style.css'
import { data } from './render'

const card = document.querySelector('.bottom img') as HTMLDivElement
const DURATION = 500

function render() {
  const shops = document.querySelector('#shops') as HTMLDivElement

  data.forEach((item, index) => {
    const shopCard = document.createElement('div')
    shopCard.classList.add('shop-card')
    const imageBox = document.createElement('div')
    const image = document.createElement('img')
    image.src = item.image
    imageBox.appendChild(image)
    shopCard.appendChild(imageBox)
    const title = document.createElement('p')
    title.classList.add('shop-title')
    title.innerText = item.title
    shopCard.appendChild(title)
    const operation = document.createElement('div')
    operation.classList.add('operation')
    const desc = document.createElement('p')
    desc.classList.add('desc')
    desc.innerText = item.desc
    operation.appendChild(desc)
    const add = document.createElement('button')
    add.classList.add('add-button')
    add.innerText = '+'
    add.setAttribute('data-index', index.toString())
    add.addEventListener('click', () => {
      const elRect = add.getBoundingClientRect()
      const rectX = elRect.left
      const rectY = elRect.top
      const index = Number(add.getAttribute('data-index'))
      parabola([rectX, rectY], data[index].image)
    })
    operation.appendChild(add)
    shopCard.appendChild(operation)
    shops.appendChild(shopCard)
  })
}

async function parabola(startP: [number, number], image: string) {
  const parabolaDom = document.createElement('div')
  const parabolaInnerDom = document.createElement('img')
  parabolaInnerDom.src = image
  parabolaDom.classList.add('parabola')
  parabolaInnerDom.classList.add('parabola-inner')
  parabolaDom.appendChild(parabolaInnerDom)
  parabolaDom.style.left = startP[0] + 'px'
  parabolaDom.style.top = startP[1] + 'px'
  document.body.appendChild(parabolaDom)
  const cardRect = card.getBoundingClientRect()
  const x = cardRect.left - startP[0]
  const y = cardRect.top - startP[1]

  parabolaDom.animate(
    [
      {
        transform: `translateX(${x}px)`
      }
    ],
    {
      duration: DURATION
    }
  )
  parabolaInnerDom.animate(
    [
      {
        transform: `translateY(${y}px)`
      }
    ],
    {
      duration: DURATION,
      easing: `cubic-bezier(0.47,-0.45, 0.89, 0.37)`
    }
  )
  setTimeout(() => {
    parabolaDom.remove()
  }, DURATION)
}

render()